<?php

namespace App\Http\Controllers\Admin\Personnel;

use App\Exports\StaffExport;
use App\Http\Controllers\Controller;
use App\Http\Requests\StaffRequest;
use Illuminate\Http\Request;
use App\Models\AdminRoleModel;
use App\Models\DeptModel;
use App\Models\StaffModel;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;
use App\Imports\StaffImport;

class Staff extends Controller
{

    use StaffRequest;

    public function list(Request $request) {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);
        $name = $request->input('name', '');
        $status = $request->input('status', '');
        $role_id = $request->input('position', 0);
        $create_start = $request->input('startTime', '');
        $create_end = $request->input('endTime', '');

        $dept_id = $request->input('department', 0);
        $dept_id2 = $request->input('dept_id', 0);



        $query = StaffModel::query()->with('role')->with('create_user:name');

        if($dept_id) {
            $query->where('dept_id', $dept_id);
        }

        if($dept_id2) {
            $query->where('dept_id', $dept_id2);
        }

        if($name) {
            $query->where('name', 'like', "%{$name}%");
        }

        if($status) {
            $query->where('status', $status);
        }

        if($role_id) {
            $query->where('role_id', $role_id);
        }

        if($create_start && $create_end){
            $query = $query->whereBetween('created_at', [$create_start, $create_end]);
        }

        $total = $query->count('id');
        $items = $query
            ->orderBy('id','desc')
            ->offset(($page-1) * $limit)
            ->limit($limit)
            ->orderBy('id', 'desc')
            ->get();

        $list = $items->map(function($item) {
            $res = [
                'id' => $item->id,
                'name' => $item->name,
                'name_en' => $item->name_en,
                'status' => $item->status,
                'status_name' => StaffModel::STATE_LIST[$item->status] ?? '',
                'dept_id' => $item->dept_id,
                'dept_name' => $item->dept ? $item->dept->name : '',
                'role_id' => $item->role_id,
                'phone' => $item->phone,
                'role' => $item->role ? $item->role->name : '',
                'created_at' => $item->created_at->toDateTimeString(),
                'create_user' => $item->create_user->name ?? '',
                'detail' => $item
            ];
            return $res;
        });

        return $this->success(['list' => $list, 'total' => $total]);
    }

    public function add(Request $request){
        $auth = $request->get('auth');
        $params = $request->all();

        $check_res = self::add_check($params);
        if($check_res->faild){
            return $this->error($check_res->err);
        }

        $role = AdminRoleModel::find($params['role_id']);
        if(!$role) {
            return $this->error('职位错误');
        }

        $dept = DeptModel::find($params['dept_id']);
        if(!$dept) {
            return $this->error('部门错误');
        }

        $staff = new StaffModel();
        $staff->status = $params['status'];
        $staff->name = $params['name'];
        $staff->name_en = $params['name_en'];
        $staff->role_id = $params['role_id'];
        $staff->dept_id = $params['dept_id'];
        $staff->is_warehouse_staff = $params['is_warehouse_staff'] ?? 0;
        $staff->warehouse_id = $params['warehouse_id'] ?? 0;
        $staff->gender = $params['gender'];
        $staff->birth_date = $params['birth_date'] ?? null;
        $staff->school_graduated = $params['school_graduated'] ?? '';
        $staff->major = $params['major'] ?? '';
        $staff->education_level = $params['education_level'] ?? '';
        $staff->native_place = $params['native_place'] ?? '';
        $staff->id_number = $params['id_number'] ?? '';
        $staff->phone = $params['phone'] ?? '';
        $staff->emergency_contact_phone = $params['emergency_contact_phone'] ?? '';
        $staff->email = $params['email'] ?? '';
        $staff->social_security_number = $params['social_security_number'] ?? '';
        $staff->housing_fund_number = $params['housing_fund_number'] ?? '';
        $staff->salary_card_number = $params['salary_card_number'] ?? '';
        $staff->first_contract_date = $params['first_contract_date'] ?? null;
        $staff->employment_start_date = $params['employment_start_date'] ?? null;
        $staff->probation_period_days = $params['probation_period_days'] ?? null;
        $staff->monthly_base_salary = $params['monthly_base_salary'] ?? null;
        $staff->position_allowance = $params['position_allowance'] ?? null;
        $staff->job_level = $params['job_level'] ?? '';
        $staff->remark = $params['remark'] ?? '';
        $staff->resignation_date = $params['resignation_date'] ?? null;
        $staff->created_admin_id = $auth->id;

        $staff->worker_number = $params['worker_number'] ?? '';
        $staff->probation_period_months = $params['probation_period_months'] ?? 0;
        $staff->turn_date = $params['turn_date'] ?? null;
        $staff->birthday = $params['birthday'] ?? null;
        $staff->age = $params['age'] ?? 0;
        $staff->home_place = $params['home_place'] ?? '';
        $staff->nationality = $params['nationality'] ?? '';
        $staff->addr_now = $params['addr_now'] ?? '';
        $staff->political_status = $params['political_status'] ?? '';
        $staff->marital_status = $params['marital_status'] ?? 0;
        $staff->emergency_contact_person = $params['emergency_contact_person'] ?? '';
        $staff->emergency_contact_relation = $params['emergency_contact_relation'] ?? '';
        $staff->work_years = $params['work_years'] ?? 0;
        $staff->work_month = $params['work_month'] ?? 0;
        $staff->year_holidays = $params['year_holidays'] ?? 0;
        $staff->contract_times = $params['contract_times'] ?? 0;
        $staff->contract_last_date = $params['contract_last_date'] ?? null;
        $staff->contract_years = $params['contract_years'] ?? 0;
        $staff->contract_end_date = $params['contract_end_date'] ?? null;
        $staff->contract_renewal_date = $params['contract_renewal_date'] ?? null;
        $staff->contract_end_remind = $params['contract_end_remind'] ?? 0;
        $staff->salary_card_bank = $params['salary_card_bank'] ?? '';
        $staff->save();

        return $this->success();
    }

    public function update(Request $request, int $id){
        $auth = $request->get('auth');
        $params = $request->all();
        $check_res = self::add_check($params);
        if($check_res->faild){
            return $this->error($check_res->err);
        }

        $staff = StaffModel::query()->find($id);
        if(!$staff) {
            return $this->error('记录不存在');
        }

        $role = AdminRoleModel::find($params['role_id']);
        if(!$role) {
            return $this->error('职位错误');
        }

        $dept = DeptModel::find($params['dept_id']);
        if(!$dept) {
            return $this->error('部门错误');
        }

        $staff->status = $params['status'];
        $staff->name = $params['name'];
        $staff->name_en = $params['name_en'];
        $staff->role_id = $params['role_id'];
        $staff->dept_id = $params['dept_id'];
        $staff->gender = $params['gender'];
        $staff->birth_date = $params['birth_date'] ?? null;
        $staff->school_graduated = $params['school_graduated'] ?? '';
        $staff->major = $params['major'] ?? '';
        $staff->education_level = $params['education_level'] ?? '';
        $staff->native_place = $params['native_place'] ?? '';
        $staff->id_number = $params['id_number'] ?? '';
        $staff->phone = $params['phone'] ?? '';
        $staff->emergency_contact_phone = $params['emergency_contact_phone'] ?? '';
        $staff->email = $params['email'] ?? '';
        $staff->social_security_number = $params['social_security_number'] ?? '';
        $staff->housing_fund_number = $params['housing_fund_number'] ?? '';
        $staff->salary_card_number = $params['salary_card_number'] ?? '';
        $staff->first_contract_date = $params['first_contract_date'] ?? null;
        $staff->employment_start_date = $params['employment_start_date'] ?? null;
        $staff->probation_period_days = $params['probation_period_days'] ?? null;
        $staff->monthly_base_salary = $params['monthly_base_salary'] ?? null;
        $staff->position_allowance = $params['position_allowance'] ?? null;
        $staff->job_level = $params['job_level'] ?? '';
        $staff->remark = $params['remark'] ?? '';
        $staff->resignation_date = $params['resignation_date'] ?? null;
        $staff->created_admin_id = $auth->id;

        $staff->worker_number = $params['worker_number'] ?? '';
        $staff->probation_period_months = $params['probation_period_months'] ?? 0;
        $staff->turn_date = $params['turn_date'] ?? null;
        $staff->birthday = $params['birthday'] ?? null;
        $staff->age = $params['age'] ?? 0;
        $staff->home_place = $params['home_place'] ?? '';
        $staff->nationality = $params['nationality'] ?? '';
        $staff->addr_now = $params['addr_now'] ?? '';
        $staff->political_status = $params['political_status'] ?? '';
        $staff->marital_status = $params['marital_status'] ?? 0;
        $staff->emergency_contact_person = $params['emergency_contact_person'] ?? '';
        $staff->emergency_contact_relation = $params['emergency_contact_relation'] ?? '';
        $staff->work_years = $params['work_years'] ?? 0;
        $staff->work_month = $params['work_month'] ?? 0;
        $staff->year_holidays = $params['year_holidays'] ?? 0;
        $staff->contract_times = $params['contract_times'] ?? 0;
        $staff->contract_last_date = $params['contract_last_date'] ?? null;
        $staff->contract_years = $params['contract_years'] ?? 0;
        $staff->contract_end_date = $params['contract_end_date'] ?? null;
        $staff->contract_renewal_date = $params['contract_renewal_date'] ?? null;
        $staff->contract_end_remind = $params['contract_end_remind'] ?? 0;
        $staff->salary_card_bank = $params['salary_card_bank'] ?? '';
        $staff->save();

        return $this->success();
    }

    public function delete(Request $request, int $id){
        $staff = StaffModel::find($id);
        if(!$staff) {
            return $this->error('记录未找到');
        }
        $staff->delete();
        return $this->success();
    }

    public function import(Request $request) {
        $auth = $request->get('auth');
        $file = $request->file('file');
        if(!$file) {
            return $this->error('请选择文件');
        }

        $import = new StaffImport();
        Excel::import($import, $file);


        $res = $import->get_result();

        if(isset($res->error) && $res->error){
            return $this->error(implode(',', $res->error));
        }

        $lines = $res->lines;

        DB::beginTransaction();
        try {
            foreach ($lines as $line){
                $staff = new StaffModel();
                foreach ($line as $k => $v){
                    $staff->$k = $v;
                }
                $staff->created_admin_id = $auth->id;
                $staff->save();
            }
        DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        return  $this->success();
    }

    public function export(Request $request) {
        $ids = $request->input('ids', []);
        if(empty($ids)){
            return $this->error('请选择要导出的数据');
        }

        $staffs = StaffModel::query()->with(['dept', 'role'])->whereIn('id', $ids)->get();

        if(!$staffs){
            return $this->error('记录未找到');
        }

        $export = $staffs->map(function ($staff, $k) {
            return [
                $k + 1,
                $staff->dept->name ?? '',
                $staff->role->name ?? '',
                $staff->name,
                $staff->name_en,
                $staff->worker_number,
                $staff->employment_start_date,
                $staff->probation_period_months,
                $staff->turn_date,
                $staff->gender,
                $staff->birth_date,
                $staff->age,
                (string)$staff->phone,
                $staff->email,
                $staff->native_place,
                (string)$staff->id_number,
                $staff->home_place,
                $staff->nationality,
                $staff->addr_now,
                $staff->education_level,
                $staff->major,
                $staff->school_graduated,
                $staff->political_status,
                $staff->marital_status,
                $staff->emergency_contact_person,
                $staff->emergency_contact_relation,
                $staff->emergency_contact_phone,
                $staff->work_years,
                $staff->work_month,
                $staff->year_holidays,
                $staff->contract_times,
                $staff->contract_last_date,
                $staff->contract_years,
                $staff->contract_end_date,
                $staff->contract_renewal_date,
                $staff->contract_end_remind,
                $staff->social_security_number,
                $staff->housing_fund_number,
                $staff->salary_card_bank,
                $staff->salary_card_number,
                $staff->remark,
                $staff->create_date,
                $staff->creator
            ];
        });


        return Excel::download(new StaffExport($export), '员工信息.xlsx');

    }

}
